#include "stm32.h"
#include "ui_stm32.h"

Stm32::Stm32(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Stm32)
{
    ui->setupUi(this);
    QObject::connect(this, SIGNAL(dataUpSignal(QByteArray)),this, SLOT(dataUpSlot(QByteArray)));
    connect(ui->pushButton_led,SIGNAL(clicked()),this,SLOT(pushButton_led_Slot()));
    connect(ui->pushButton_led_2,SIGNAL(clicked()),this,SLOT(pushButton_fan_Slot()));
    //                     connect(ui->pushButton_led_3,SIGNAL(clicked()),this,SLOT(pushButton_beep_Slot()));
    //                     connect(ui->pushButton_led_4,SIGNAL(clicked()),this,SLOT(pushButton_lin_Slot()));

    setupRealtimeDataDemo(ui->customPlot);
    ui->customPlot->replot();

    ui->checkBox_temp->setChecked(true);
    ui->checkBox_hum->setChecked(true);



    //    long timestamp = 1666482615;
    // 使用QDateTime::fromSecsSinceEpoch将时间戳转换为QDateTime对象
    // 将QDateTime对象转换为字符串格式的日期和时间
    //       QString dateTimeStr = QDateTime::fromMSecsSinceEpoch(timestamp).toString("yyyy-MM-dd HH:mm:ss");

    //       // 输出转换后的日期时间字符串
    //       qDebug() << "转换后的日期时间：" << dateTimeStr;
//    ui->pushButton_led->setStyleSheet("background-color: rgb(71, 126, 255);");
//    ui->pushButton_led_2->setStyleSheet("background-color: rgb(71, 126, 255);");
    connect(ui->pushButton_led_3,SIGNAL(clicked()),this,SLOT(pushButton_3_shuaxin()));

}

Stm32::~Stm32()
{
    delete ui;
}

//画图初始化
void Stm32::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
    //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
    //#endif
    //demoName = "Real Time Data Demo";

    // include this section to fully disable antialiasing for higher performance:
    /*
     customPlot->setNotAntialiasedElements(QCP::aeAll);
     QFont font;
     font.setStyleStrategy(QFont::NoAntialias);
     customPlot->xAxis->setTickLabelFont(font);
     customPlot->yAxis->setTickLabelFont(font);
     customPlot->legend->setFont(font);
     */
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(Qt::blue));
    customPlot->graph(0)->setName("temp");
    //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
    //customPlot->graph(0)->setAntialiasedFill(false);
    customPlot->addGraph(); // red line
    customPlot->graph(1)->setPen(QPen(Qt::red));
    customPlot->graph(1)->setName("hum");
    //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("MM-dd hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(2);
    customPlot->axisRect()->setupFullAxesBox();

    // make left and bottom axes transfer their ranges to right and top axes:
    //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
    connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
    dataTimer.start(1000); // Interval 0 means to refresh as fast as possible
    customPlot->legend->setVisible(true);
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);//可以进行鼠标位置 放大缩小 拖拽  放大缩小坐标系

}
//接收数据并显示
void Stm32::dataUpSlot(QByteArray text)
{
    QString value(text);
    QJsonParseError parseJsonErr;
    QJsonDocument document = QJsonDocument::fromJson(value.toUtf8(),&parseJsonErr);
    QJsonObject jsonObject = document.object();
    qDebug()<<"type="<<jsonObject["type"].toInt();

    if(jsonObject.contains(QStringLiteral("result")))
    {
        QJsonValue jsonValueList = jsonObject.value(QStringLiteral("result"));
        QJsonObject item = jsonValueList.toObject();
        qDebug()<<"result="<<item["result"].toInt();
    }

    if(jsonObject.contains(QStringLiteral("data")))
    {
        QJsonValue arrayValue = jsonObject.value(QStringLiteral("data"));
        if(arrayValue.isArray())
        {
            QJsonArray array = arrayValue.toArray();
            for(int i=0;i<array.size();i++)
            {
                QJsonValue iconArray = array.at(i);
                QJsonObject icon = iconArray.toObject();
                int key = icon["key"].toInt();
                QString val = icon["val"].toString();
                qDebug()<<"key="<<key<<"val="<<val;

                switch (key) {
                case 301:
                    ui->lineEdit->setText(val);
                    temp=val.toDouble();
                    break;
                case 302:
                    ui->lineEdit_2->setText(val);
                    hum=val.toDouble();
                    break;
                case 303:
                    ui->lineEdit_3->setText(val);
                    break;
                case 304://通风系统
                    if(val == "0")
                    {
//                        ui->pushButton_led_2->setStyleSheet("background-color: rgb(71, 126, 255);");
                        ui->pushButton_led_2->setChecked(false);
                        tongfeng=0;
                    }
                    else if((val == "1"))
                    {
//                        ui->pushButton_led_2->setStyleSheet("background-color: rgb(255, 174, 60);");
                        ui->pushButton_led_2->setChecked(true);
                        tongfeng=1;
                    }
                    else
                    {

                    }
                    break;
                case 306://报警
                    if(val == "0")
                    {
                        ui->pushButton_baojing->setChecked(false);
                    }
                    else if((val == "1"))
                    {
                        ui->pushButton_baojing->setChecked(true);
                    }
                    else
                    {

                    }
                    break;
                case 307://灯
                    if(val == "0")
                    {
                        //                         ui->pushButton_led->setStyleSheet("QPushButton{background-image: url(:/new/prefix1/pic/kaideng.png)}");
//                        ui->pushButton_led->setStyleSheet("background-color: rgb(71, 126, 255);");
                        ui->pushButton_led->setChecked(false);
                        deng=0;

                    }
                    else if(val == "1")
                    {
//                        ui->pushButton_led->setStyleSheet("background-color: rgb(255, 174, 60);");
                        ui->pushButton_led->setChecked(true);
                        deng=1;
                    }
                    else
                    {

                    }
                    break;
                case 308://喷淋系统
                    if(val == "0")
                    {
                        ui->pushButton_penlin->setChecked(false);
                    }
                    else if((val == "1"))
                    {
                        ui->pushButton_penlin->setChecked(true);
                    }
                    else
                    {

                    }
                    break;
                default:
                    break;
                }

            }
        }
    }
}
//控制灯槽函数
void Stm32::pushButton_led_Slot()
{
    if(deng==1)
    {
//        ui->pushButton_led->setStyleSheet("background-color: rgb(71, 126, 255);");
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"307\",\"val\": \"0\"}}");
        GlobalVal::mqtt->publish(aaa);
        deng=0;
    }
    else
    {
//        ui->pushButton_led->setStyleSheet("background-color: rgb(255, 174, 60);");
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"307\",\"val\": \"1\"}}");
        GlobalVal::mqtt->publish(aaa);
        deng=1;
    }

}
//控制通风系统
void Stm32::pushButton_fan_Slot()
{
    if(tongfeng==1)
    {
//        ui->pushButton_led_2->setStyleSheet("background-color: rgb(71, 126, 255);");
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"304\",\"val\": \"0\"}}");
        GlobalVal::mqtt->publish(aaa);
        tongfeng=0;
    }
    else
    {
//        ui->pushButton_led_2->setStyleSheet("background-color: rgb(255, 174, 60);");
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"304\",\"val\": \"1\"}}");
        GlobalVal::mqtt->publish(aaa);
        tongfeng=1;
    }
}
//控制报警系统
void Stm32::pushButton_beep_Slot()
{
    if(baojing==1)
    {
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"306\",\"val\": \"0\"}}");
        GlobalVal::mqtt->publish(aaa);
        baojing=0;
    }
    else
    {
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"306\",\"val\": \"1\"}}");
        GlobalVal::mqtt->publish(aaa);
        baojing=1;
    }
}
//控制喷淋系统
void Stm32::pushButton_lin_Slot()
{
    if(penlin==1)
    {
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"308\",\"val\": \"0\"}}");
        GlobalVal::mqtt->publish(aaa);
        penlin=0;
    }
    else
    {
        QMQTT::Message aaa;
        aaa.setTopic("down");
        aaa.setPayload("{\"type\": 2, \"data\": { \"key\": \"308\",\"val\": \"1\"}}");
        GlobalVal::mqtt->publish(aaa);
        penlin=1;
    }
}


void Stm32::realtimeDataSlot()
{
    //key的单位是秒
    double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
    //      double value0 = qrand() % 100;
    //      double value1 = qrand() % 80;
    //      if (ui->checkBox_temp->isChecked())
    //          ui->customPlot->graph(0)->addData(key, value0);//添加数据1到曲线1
    //      if (ui->checkBox_hum->isChecked())
    //          ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2

    //      double value0 = qrand() % 100;
    //      double value1 = qrand() % 80;
    if (ui->checkBox_temp->isChecked())
        ui->customPlot->graph(0)->addData(key, temp);//添加数据1到曲线1
    if (ui->checkBox_hum->isChecked())
        ui->customPlot->graph(1)->addData(key, hum);//添加数据2到曲线2

    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
    ui->customPlot->graph(0)->removeDataBefore(key-15);
    ui->customPlot->graph(1)->removeDataBefore(key-15);

    //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
    //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
    ui->customPlot->graph(0)->rescaleValueAxis();
    ui->customPlot->graph(1)->rescaleValueAxis(true);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
    //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
    ui->customPlot->xAxis->setRange(key+0.25, 15, Qt::AlignRight);//设定x轴的范围
    ui->customPlot->xAxis->setTickLabelRotation(10);//设置刻度标签顺时针旋转10度
    ui->customPlot->replot();
    timer = new QTimer(this);

    // 提前刷新显式控件
    timeoutSlot();

    timer->setInterval(500);   // 设置时间间隔1秒钟
    timer->setSingleShot(false);    // 为周期循环

    // 连接信号槽要在启动定时器之前连接
    connect(timer,SIGNAL(timeout()),this,
        SLOT(timeoutSlot()));

    // 启动定时器
    timer->start();
}


//刷新
void Stm32::pushButton_3_shuaxin()
{
    QMQTT::Message aaa;
    aaa.setTopic("down");
    aaa.setPayload("{\"type\": 1,\"limit\": \"all\",\"keys\": [301, 302, 303, 304 , 305, 306, 307, 308, 101, 102, 103, 104, 105, 106]}");
    GlobalVal::mqtt->publish(aaa);
}

void Stm32::timeoutSlot()
{
    // 获取当前系统时间，转换为：时:分:秒
        QString str = QDateTime::currentDateTime().toString("hh:mm:ss");
        ui->lcdNumber->display(str);
}













